<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use \App\Model\Job\Job;
use Illuminate\Support\Collection;

class JobController extends Controller
{
    public function create()
    {
        $job = new Job();
        $job->uid = auth()->id();
        $job->parent_job_id = request('parentJobId', 0);
        $job->path = '';
        $job->title = request('title');
        $job->content = request('content', '');
        $job->save();
        $job->updatePath();

        return $this->response($job);
    }

    public function update($id)
    {
        /**
         * @var Job $job
         */
        $job = Job::whereUid(auth()->id())->findOrFail($id);
        if (!empty(request('parentJobId'))) {
            $job->parent_job_id = request('parentJobId');
        }
        if (!empty(request('title'))) {
            $job->title = request('title');
        }
        if (!empty(request('content'))) {
            $job->content = request('content');
        }

        $job->save();
        $job->updatePath();

        return $this->response($job);
    }

    public function list()
    {
        $model = Job::query();
        $model->where('uid', auth()->id());
        if (!empty(request('id'))) {
            $model->where('id', request('id'));
        }
        if (!empty(request('parentJobId'))) {
            $model->where('parent_job_id', request('parentJobId'));
        }
        if (!empty(request('title'))) {
            $model->where('title', request('title'));
        }
        if (!empty(request('content'))) {
            $model->where('content', request('content'));
        }

        $jobs = $model->get();
        $rs = $this->toJobs($jobs);

        return $this->response($rs);
    }

    /**
     * @param $jobs
     * @param int $parentId
     * @return array
     */
    public function toJobs($jobs, $parentId = '0')
    {
        $arr = collect($jobs)->filter(function ($job) use ($parentId) {
            return $job['parent_job_id'] == $parentId;
        })->map(function ($job) {
            return [
                'id'          => $job['id'],
                'parentJobId' => $job['parent_job_id'],
                'path'        => $job['path'],
                'title'       => $job['title'],
                'content'     => $job['content'],
                'createdAt'   => (string)$job['created_at'],
            ];
        })->values()
          ->all();

        foreach ($arr as $k => $v) {
            $arr[$k]['children'] = $this->toJobs($jobs, $v['id']);
        }

        return $arr;

    }

    public function find($id)
    {
        $rs = Job::whereUid(auth()->id())->find($id);

        return $this->response($rs);
    }

    public function delete($id)
    {
        $job = Job::whereUid(auth()->id())->findOrFail($id);
        $rs = Job::query()->where('path','like', $job->path . '%')->delete();

        return $this->response($rs);
    }
}
